﻿using System;
using ePlanet.ArchiveMange.Enum;
using ePlanet.ArchiveMange.Models;
using ePlanet.ArchiveMange.Services;
using ePlanet.ArchiveBorrow.Services;
using ePlanet.ArchiveBorrow.Models;
using ePlanet.ArchiveBorrow.Enum;
using Microsoft.Practices.Unity;
using Web.SystemLogin.Models;
using Web.SystemConfig.WorkFlow;
using Web.SystemConfig.SysCache;
using System.Collections;
using System.Data;
using System.Collections.Generic;
using DreamBuilder.Core.Container;
using Web.SystemConfig.Services;
using System.Web.UI.WebControls;
using Wuqi.Webdiyer;
using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.Services;

namespace Web.Views.ArchiveBorrow.ArchiveBorrowApply
{
    public partial class ArchiveBorrowApplyList : PageBase
    {
        #region 依赖注入服务
        [Dependency]
        public IArchiveMenuService m_IArchiveMenuService
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_User m_IAuth_User
        {
            get;
            set;
        }

        [Dependency]
        public IArchiveBorrowService m_IArchiveBorrowService
        {
            get;
            set;
        }

        [Dependency]
        public ICodeTable m_ICodeTableService
        {
            get;
            set;
        }
        #endregion

        #region 私有属性
        private User m_CurrentUser
        {
            get
            {
                return (Web.SystemLogin.Models.User)Session["CurrentUser"];
            }
        }

        private ArchiveTableEnum m_ArchiveBaseType
        {
            get
            {
                int archiveTypeID = 0;
                if (Request.QueryString["archivetype"] != null)
                {
                    string archiveType = Request.QueryString["archivetype"];
                    if (int.TryParse(archiveType, out archiveTypeID))
                    {
                        if (archiveTypeID == -1)
                        {
                            this.btnNewBorrow.Visible = false;
                            this.btnSearch.Visible = false;
                            this.btnReset.Visible = false;
                            this.uArchiveFileter.Visible = false;
                        }
                        return (ArchiveTableEnum)archiveTypeID;
                    }
                    else
                    {
                        throw new Exception("档案类型错误");
                    }
                }
                else
                {
                    throw new Exception("档案类型不能为空");
                }
            }
        }

        private ArchiveBorrowModel m_ArchiveBorrowModel = null;

        /// <summary>
        /// 是否场厂内厂外的借阅逻辑
        /// </summary>
        private bool IsOldArchiveBorrow
        {
            get
            {
                if (string.Equals(Request.QueryString["isBase"], "true", StringComparison.InvariantCultureIgnoreCase))
                {
                    return false;
                }
                return true;
            }
        }
        #endregion

        #region 页面事件
        protected void Page_Load(object sender, EventArgs e)
        {
            this.cblUSERTYPE.Attributes.Add("onclick", "Selectfuzhi()");
            if (this.cblUSERTYPE.SelectedIndex == this.cblUSERTYPE.Items.Count - 1)
            {
                this.trCopyPage.Attributes.CssStyle.Remove("display");
            }
            else
            {
                this.trCopyPage.Attributes.CssStyle.Add("display", "none");
            }

            if (IsOldArchiveBorrow)
            {
                if (IsDAY())
                {
                    this.trDown.Visible = false;
                    this.txtBorrowUser.Enabled = true;
                }
            }
            else
            {
                if (IsJicengDAY())
                {
                    this.trDown.Visible = false;
                    this.txtBorrowUser.Enabled = true;
                }
            }

            int archiveTypeID = 0;
            if (int.TryParse(Request.QueryString["archivetype"], out archiveTypeID))
            {
                if (archiveTypeID == -1)
                {
                    this.btnNewBorrow.Visible = false;
                    this.btnSearch.Visible = false;
                    this.btnReset.Visible = false;
                    this.uArchiveFileter.Visible = false;
                    this.btnApplyNewRequest.Visible = false;
                    this.btnGiveUp.Visible = false;
                }
                if (!IsPostBack)
                {
                    btnSearch_Click(null, null);
                }
            }
            else
            {
                throw new Exception("档案类型错误");
            }
            this.uArchiveFileter.AfterFiltered += new EventHandler(OnAfterFiltered_Click);
            this.uArchiveFileter.ClearFiltered += new EventHandler(OnClearFiltered_Click);
        }

        /// <summary>
        /// 是否信息中心档案员
        /// </summary>
        /// <returns></returns>
        private bool IsDAY()
        {
            IAuth_Role oIAuth_Role = UContainer.Resolve<IAuth_Role>();
            return oIAuth_Role.IsThisRole(this.m_CurrentUser.User_ID, "52");
        }

        /// <summary>
        /// 是否基层档案员
        /// </summary>
        /// <returns></returns>
        private bool IsJicengDAY()
        {
            IAuth_Role oIAuth_Role = UContainer.Resolve<IAuth_Role>();
            return oIAuth_Role.IsThisRole(this.m_CurrentUser.User_ID, "112");
        }

        /// <summary>
        /// 选择数据，申请访问
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNewBorrow_Click(object sender, EventArgs e)
        {
            NewBorrow();
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            //DataTable oDataTable = this.GetTotal();
            //this.uArchiveFileter.ArchiveSourceTable = oDataTable;
            //this.uArchiveFileter.DataBind();

            //DataTable oDataTable2 = this.uArchiveFileter.ArchiveFilteredTable;
            //SetGridViewEnableField(oDataTable2);
            //this.gv_ArchiveList.DataSource = oDataTable2;
            //this.DataBind();
            this.pagerdo.CurrentPageIndex = 1;
            BindFilterData();
        }

        private void SetGridViewEnableField(DataTable oDataTable)
        {
            if (oDataTable != null)
            {
                foreach (DataControlField dataControlField in this.gv_ArchiveList.Columns)
                {
                    if (dataControlField is BoundField)
                    {
                        BoundField boundField = dataControlField as BoundField;
                        if (boundField != null)
                        {
                            bool flag = false;
                            foreach (DataColumn col in oDataTable.Columns)
                            {
                                if (boundField.DataField.ToLower() == col.ColumnName.ToLower())
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag)
                            {
                                boundField.Visible = false;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 重置数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReset_Click(object sender, EventArgs e)
        {

        }

        protected void btnDAYNewBorrow_Click(object sender, EventArgs e)
        {
            try
            {
                this.BindArchiveDataToSelectGV();
                this.divSearch.Visible = false;
                this.divSelectData.Visible = true;
                this.btnGiveUp.Visible = true;
                this.btnApplyNewRequest.Visible = true;

                this.btnReset.Visible = false;
                this.btnSearch.Visible = false;
                this.btnNewBorrow.Visible = false;

                this.txtBorrowUser.Text = this.m_CurrentUser.User_Name;
                this.txtBorrowTime.Text = DateTime.Now.ToShortDateString();

                string userID = this.m_CurrentUser.User_ID;
                this.txtBorrowUser.Text = UContainer.Resolve<IAuth_User>().GetUserNameById(userID);
                DataTable orgTable = UContainer.Resolve<IAuth_User>().CheckOrgInfo(userID);
                if (orgTable != null && orgTable.Rows.Count > 0)
                {
                    this.txtBorrowUserOrg.Text = string.Concat(orgTable.Rows[0]["ORG_Name"]);
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        /// <summary>
        /// 放弃申请
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnGiveUp_Click(object sender, EventArgs e)
        {
            GiveUp();
        }

        /// <summary>
        /// 生成借阅单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCreateBorrowSheet_Click(object sender, EventArgs e)
        {
            ApplyNewBorrow(BorrowType.BorrowChangnei, true);//BorrowChangnei参数在后面代码无效。
            ArrayList SelectItemList = this.gv_ArchiveList.SelectItems;
            if (SelectItemList != null && SelectItemList.Count > 0)
            {
                if (this.CreateSession(SelectItemList))
                {
                    Response.Redirect("../PrintLineDownArchiveBorrowList.aspx?BorrowDataType=" + ((int)this.m_ArchiveBaseType).ToString());
                }
            }
            else
            {
                Alert("请先选择档案后再执行此操作");
            }
        }

        /// <summary>
        /// 修改在线打印页面传值逻辑.带上所有录入好的数据.
        /// </summary>
        private bool CreateSession(ArrayList SelectItemList)
        {
            PrintModel oPrintModel = new PrintModel();
            oPrintModel.BorrowReason = this.txtReason.Text.Trim();
            oPrintModel.ExpridTime = this.txtValidPeriod.Text.Trim();
            oPrintModel.IDCard = this.txtIDCARD.Text.Trim();
            oPrintModel.TelNum = this.txtTELNUM.Text.Trim();
            oPrintModel.UserName = this.txtBorrowUser.Text.Trim();
            oPrintModel.UserOrg = this.txtBorrowUserOrg.Text.Trim();
            foreach (ListItem item in this.cblARCHIVETYPE.Items)
            {
                if (item.Selected)
                {
                    oPrintModel.ArchiveType.Add(item.Value);
                }
            }
            foreach (ListItem item in this.cblUSERTYPE.Items)
            {
                if (item.Selected)
                {
                    oPrintModel.UserType.Add(item.Value);
                    //若选了复制，则填写复制的内容
                    if (this.cblUSERTYPE.Items.IndexOf(item) == this.cblUSERTYPE.Items.Count - 1)
                    {
                        oPrintModel.CopyPage = this.txtCopyPage.Text.Trim();
                    }
                }
            }
            foreach (string dataId in SelectItemList)
            {
                oPrintModel.DataList.Add(dataId);
            }
            Session["PrintModel"] = oPrintModel;

            return true;
        }

        private void NewPageOpen(string url)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>$(function(){window.open('" + url + "')});</script>");
        }

        /// <summary>
        /// 确定申请
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnApplyNewRequest_Click(object sender, EventArgs e)
        {
            if (IsOldArchiveBorrow)
            {
                ApplyNewBorrow(IsDAY() ? BorrowType.BorrowChangwai : BorrowType.BorrowChangnei);
            }
            else
            {
                ApplyNewBorrow(IsJicengDAY() ? BorrowType.BorrowJicengdaili : BorrowType.BorrowJiceng);
            }
        }

        protected void gv_ArchiveList_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.DataItem != null)
                {
                    DataRow row = ((DataRowView)e.Row.DataItem).Row;
                    //e.Row.Cells[3].Text = IUserService.GetUserNameById(row["CREATEUSERID"].ToString());
                    e.Row.Cells[2].Text = m_ICodeTableService.GetpkNameByCodepkValue(row["F_SECURITYTYPE"].ToString());
                    e.Row.Cells[3].Text = m_ICodeTableService.GetpkNameByCodepkValue(row["F_KEEPTIME"].ToString());
                    //e.Row.Cells[8].Text = orgService.GetOrgNameByOrgID(drv["FIleOrgID"].ToString());
                    e.Row.Cells[6].Text = m_ICodeTableService.GetpkNameByCodepkValue(row["F_CARRIERTYPE"].ToString());
                }
            }
        }

        protected void gv_SelectArchiveDataList_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.DataItem != null)
                {
                    DataRow row = ((DataRowView)e.Row.DataItem).Row;
                    //e.Row.Cells[3].Text = IUserService.GetUserNameById(row["CREATEUSERID"].ToString());
                    e.Row.Cells[1].Text = m_ICodeTableService.GetpkNameByCodepkValue(row["F_SECURITYTYPE"].ToString());
                    e.Row.Cells[2].Text = m_ICodeTableService.GetpkNameByCodepkValue(row["F_KEEPTIME"].ToString());
                    //e.Row.Cells[8].Text = orgService.GetOrgNameByOrgID(drv["FIleOrgID"].ToString());
                    e.Row.Cells[4].Text = m_ICodeTableService.GetpkNameByCodepkValue(row["F_CARRIERTYPE"].ToString());
                }
            }
        }
        #endregion

        #region 私有方法

        #region 按钮方法
        private void ApplyNewBorrow(BorrowType borrowType, bool isPaper = false)
        {
            try
            {
                if (this.gv_ArchiveList.DataSource == null)
                {
                    Alert("请先查询数据，然后提交申请！");
                }
                else
                {
                    this.CollectData(borrowType);
                    if (this.m_ArchiveBorrowModel != null)
                    {
                        this.m_IArchiveBorrowService.InsertNewArchiveBorrowModel(this.m_ArchiveBorrowModel);
                        if (!isPaper)
                        {
                            foreach (ArchiveBorrowModel.ARCHIVEBORROWRow row in this.m_ArchiveBorrowModel.ARCHIVEBORROW.Rows)
                            {
                                switch (borrowType)
                                {
                                    case BorrowType.BorrowChangnei:
                                        this.ProcessWorkFlow(row, ArchiveBorrowEnum.发起借阅);
                                        break;
                                    case BorrowType.BorrowChangwai:
                                        this.ProcessWorkFlow(row, ArchiveBorrowEnum.档案员发起借阅);
                                        break;
                                    case BorrowType.BorrowJiceng:
                                        this.ProcessWorkFlow(row, ArchiveBorrowEnum.基层发起借阅);
                                        break;
                                    case BorrowType.BorrowJicengdaili:
                                        this.ProcessWorkFlow(row, ArchiveBorrowEnum.基层档案员发起借阅);
                                        break;
                                }
                            }
                        }
                        else
                        {
                            //纸质文档节约，启用新流程
                            foreach (ArchiveBorrowModel.ARCHIVEBORROWRow row in this.m_ArchiveBorrowModel.ARCHIVEBORROW.Rows)
                            {
                                this.ProcessWorkFlow(row, ArchiveBorrowEnum.纸质文档借阅);
                            }
                        }

                        if (!isPaper)
                        {
                            string url = string.Format("ArchiveBorrowApplyList.aspx?archivetype={0}&IsBase={1}", Request.QueryString["archivetype"], !IsOldArchiveBorrow);
                            MyAlert("申请访问成功", url);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        private void NewBorrow()
        {
            try
            {
                this.BindArchiveDataToSelectGV();
                this.divSearch.Visible = false;
                this.divSelectData.Visible = true;
                this.btnGiveUp.Visible = true;
                this.btnApplyNewRequest.Visible = true;

                this.btnReset.Visible = false;
                this.btnSearch.Visible = false;
                this.btnNewBorrow.Visible = false;

                this.txtBorrowUser.Text = this.m_CurrentUser.User_Name;
                this.txtBorrowTime.Text = DateTime.Now.ToShortDateString();

                string userID = this.m_CurrentUser.User_ID;
                this.txtBorrowUser.Text = UContainer.Resolve<IAuth_User>().GetUserNameById(userID);
                DataTable orgTable = UContainer.Resolve<IAuth_User>().CheckOrgInfo(userID);
                if (orgTable != null && orgTable.Rows.Count > 0)
                {
                    this.txtBorrowUserOrg.Text = string.Concat(orgTable.Rows[0]["ORG_Name"]);
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 是否相同密级
        /// </summary>
        /// <param name="dataIDList"></param>
        /// <returns></returns>
        private bool IsSameSetret(List<Guid> dataIDList)
        {
            bool rtnBool = false;
            switch (this.m_ArchiveBaseType)
            {
                case ArchiveTableEnum.Account:
                case ArchiveTableEnum.AccountI01:
                case ArchiveTableEnum.AccountI02:
                case ArchiveTableEnum.AccountI03:
                case ArchiveTableEnum.AccountI04:
                    IAccountArchiveService oIAccountArchiveService = UContainer.Resolve<IAccountArchiveService>();
                    rtnBool = oIAccountArchiveService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.AudioVedio:
                case ArchiveTableEnum.AudioVedioS01:
                case ArchiveTableEnum.AudioVedioS02:
                case ArchiveTableEnum.AudioVedioS03:
                    IAudioArchiveService oIAudioArchiveService = UContainer.Resolve<IAudioArchiveService>();
                    rtnBool = oIAudioArchiveService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.BulidProject:
                    IBuildProjectArchiveService oIBuildProjectArchiveService = UContainer.Resolve<IBuildProjectArchiveService>();
                    rtnBool = oIBuildProjectArchiveService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.CDKind:
                    ICDArchiveService oICDArchiveService = UContainer.Resolve<ICDArchiveService>();
                    rtnBool = oICDArchiveService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.Document:
                    IDocumentArchiveService oIDocumentArchiveService = UContainer.Resolve<IDocumentArchiveService>();
                    rtnBool = oIDocumentArchiveService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.Document_Archive_Vol:
                    IDocumentArchiveVolService oIDocumentArchiveVolService = UContainer.Resolve<IDocumentArchiveVolService>();
                    rtnBool = oIDocumentArchiveVolService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.Document_Archive_Vol_File:
                    IDocumentArchiveVolFileService oIDocumentArchiveVolFileService = UContainer.Resolve<IDocumentArchiveVolFileService>();
                    rtnBool = oIDocumentArchiveVolFileService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.Equipment:
                    IEquipmentService oIEquipmentService = UContainer.Resolve<IEquipmentService>();
                    rtnBool = oIEquipmentService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.OliSearch:
                case ArchiveTableEnum.OliSearchK01:
                case ArchiveTableEnum.OliSearchK02:
                case ArchiveTableEnum.OliSearch_Zonghe_Vol:
                case ArchiveTableEnum.OliSearch_Zonghe_Vol_File:
                    IOilSearchArchiveService oIOilSearchArchiveService = UContainer.Resolve<IOilSearchArchiveService>();
                    rtnBool = oIOilSearchArchiveService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.RealKind:
                case ArchiveTableEnum.RealKindR01:
                case ArchiveTableEnum.RealKindR02:
                case ArchiveTableEnum.RealKindR03:
                case ArchiveTableEnum.RealKindR04:
                    IRealKindArchiveService oIRealKindArchiveService = UContainer.Resolve<IRealKindArchiveService>();
                    rtnBool = oIRealKindArchiveService.IsSameSecret(dataIDList);
                    break;
                case ArchiveTableEnum.Technology:
                    ITechArchiveService oITechArchiveService = UContainer.Resolve<ITechArchiveService>();
                    rtnBool = oITechArchiveService.IsSameSecret(dataIDList);
                    break;
                default:
                    throw new Exception("未知的文档类型");
            }
            return rtnBool;
        }

        /// <summary>
        /// 收集选择的数据
        /// </summary>
        private void CollectData(BorrowType borowType)
        {
            DataTable selectData = this.gv_SelectArchiveDataList.DataSource as DataTable;
            if (selectData != null && selectData.Rows.Count > 0)
            {
                this.m_ArchiveBorrowModel = new ArchiveBorrowModel();
                string orderID = string.Empty;
                if (!this.m_IArchiveBorrowService.GetNewOrderID(out orderID))
                {
                    throw new Exception("创建新编号失败");
                }

                foreach (DataRow dr in selectData.Rows)
                {
                    ArchiveBorrowModel.ARCHIVEBORROWRow row = this.m_ArchiveBorrowModel.ARCHIVEBORROW.NewARCHIVEBORROWRow();
                    row.ARCHIVETYPEID = (int)this.m_ArchiveBaseType;//档案类型
                    row.ARCHIVEDATAID = dr["DataID"].ToString();
                    row.CANDOWNLOAD = this.cboCanDownload.Checked == true ? 1 : 0;
                    row.CANVIEW = this.cboCanView.Checked == true ? 1 : 0;
                    row.CREATETIME = DateTime.Now;
                    row.DATAID = Guid.NewGuid().ToString();
                    row.ISPAPERARCHIVE = 0;
                    row.ISPAPERARCHIVERETURN = 0;
                    row.ORDERID = orderID;
                    row.BORROWREASON = this.txtReason.Text.Trim();
                    row.USERORGNAME = this.txtBorrowUserOrg.Text;
                    if (string.IsNullOrEmpty(this.txtBorrowUser.Text.Trim()))
                    {
                        throw new Exception("利用者不能为空");
                    }
                    row.BORROWUSERNAME = this.txtBorrowUser.Text.Trim();
                    row.SetRETURNTIMENull();
                    row.STATUSID = 0;
                    row.CREATEUSERID = this.m_CurrentUser.User_ID;
                    DateTime VALIDPERIOD = DateTime.Now.Date;
                    //添加借阅类型，是厂外还是厂内
                    //Add 添加基层借阅逻辑
                    row.BOROWTYPE = (int)borowType;

                    //利用方式
                    if (this.cblUSERTYPE.SelectedItem == null)
                    {
                        throw new Exception("请选择利用方式");
                    }
                    else
                    {
                        string strUSERTYPE = string.Empty;
                        foreach (ListItem item in this.cblUSERTYPE.Items)
                        {
                            if (item.Selected)
                            {
                                strUSERTYPE += item.Value + ",";
                                //若选了复制，则填写复制的内容
                                if (this.cblUSERTYPE.Items.IndexOf(item) == this.cblUSERTYPE.Items.Count - 1)
                                {
                                    if (!string.IsNullOrEmpty(this.txtCopyPage.Text.Trim()))
                                    {
                                        row.COPYPAGE = this.txtCopyPage.Text.Trim();
                                    }
                                    else
                                    {
                                        throw new Exception("请填写复制页数");
                                    }
                                }
                            }
                        }
                        if (strUSERTYPE.EndsWith(","))
                        {
                            strUSERTYPE = strUSERTYPE.Remove(strUSERTYPE.Length - 1, 1);
                        }

                        row.USERTYPE = strUSERTYPE;
                    }

                    //档案类型
                    if (this.cblARCHIVETYPE.SelectedItem == null)
                    {
                        throw new Exception("请选择档案类型");
                    }
                    else
                    {
                        string strARCHIVETYPE = string.Empty;
                        foreach (ListItem item in this.cblARCHIVETYPE.Items)
                        {
                            if (item.Selected)
                            {
                                strARCHIVETYPE += item.Value + ",";
                            }
                        }

                        if (strARCHIVETYPE.EndsWith(","))
                        {
                            strARCHIVETYPE = strARCHIVETYPE.Remove(strARCHIVETYPE.Length - 1, 1);
                        }

                        row.ARCHIVETYPE = strARCHIVETYPE;
                        
                        if (strARCHIVETYPE.IndexOf("2") >= 0)
                            row.ISPAPERARCHIVE = 1;
                    }

                    //证件名称及编号
                    if (string.IsNullOrEmpty(this.txtIDCARD.Text.Trim()))
                    {
                        throw new Exception("请填写证件名称及编号");
                    }
                    else
                    {
                        row.IDCARD = this.txtIDCARD.Text.Trim();
                    }

                    if (string.IsNullOrEmpty(this.txtTELNUM.Text.Trim()))
                    {
                        throw new Exception("请填写联系电话");
                    }
                    else
                    {
                        row.TELNUM = this.txtTELNUM.Text.Trim();
                    }

                    if (DateTime.TryParse(this.txtValidPeriod.Text, out VALIDPERIOD))
                    {
                        if (VALIDPERIOD <= DateTime.Now.Date)
                        {
                            throw new Exception("选择的日期必须大于当前日期");
                        }
                        else
                        {
                            row.VALIDPERIOD = VALIDPERIOD;
                        }

                    }
                    else
                    {
                        throw new Exception("请填写正确格式的过期时间");
                    }

                    this.m_ArchiveBorrowModel.ARCHIVEBORROW.AddARCHIVEBORROWRow(row);
                }
            }
            else
            {
                throw new Exception("请先选择文档数据");
            }
        }

        /// <summary>
        /// 绑定选择的数据到选择列表
        /// </summary>
        private void BindArchiveDataToSelectGV()
        {
            this.gv_SelectArchiveDataList.DataSource = null;
            this.gv_SelectArchiveDataList.DataBind();
            ArrayList SelectItemList = this.gv_ArchiveList.SelectItems;
            if (SelectItemList != null && SelectItemList.Count > 0)
            {
                List<Guid> dataIDList = new List<Guid>();
                foreach (string key in SelectItemList)
                {
                    Guid dataID = new Guid(key);
                    dataIDList.Add(dataID);
                }

                //判断是否相同密级
                if (!IsSameSetret(dataIDList))
                {
                    throw new Exception("请选择相同密级的数据");
                }

                DataTable originalData = this.gv_ArchiveList.DataSource as DataTable;
                DataTable selectData = originalData.Clone();

                foreach (string key in SelectItemList)
                {
                    DataRow[] originalRows = originalData.Select(string.Format("DataID='{0}'", key));
                    if (originalRows != null && originalRows.Length > 0)
                    {
                        DataRow newRow = selectData.NewRow();
                        foreach (DataColumn col in selectData.Columns)
                        {
                            newRow[col] = originalRows[0][col.ColumnName];
                        }
                        selectData.Rows.Add(newRow);
                    }
                }

                if (selectData != null && selectData.Rows.Count > 0)
                {
                    this.gv_SelectArchiveDataList.DataSource = selectData;
                    this.gv_SelectArchiveDataList.DataBind();
                }
                else
                {
                    throw new Exception("请先选择数据，然后在提交申请。");
                }
            }
            else
            {
                throw new Exception("请先选择数据，然后在提交申请");
            }
        }

        private void GiveUp()
        {
            this.btnGiveUp.Visible = false;
            this.btnApplyNewRequest.Visible = false;
            this.btnReset.Visible = false;
            this.btnSearch.Visible = false;
            this.btnNewBorrow.Visible = true;
            this.divSearch.Visible = true;
            this.divSelectData.Visible = false;
        }
        #endregion

        #region 流程操作
        /// <summary>
        /// 流程驱动
        /// </summary>
        /// <param name="row"></param>
        /// <param name="borrowEnum"></param>
        private void ProcessWorkFlow(ArchiveBorrowModel.ARCHIVEBORROWRow row, ArchiveBorrowEnum borrowEnum)
        {
            var oWorkFlowModel = new WorkFlowModel();
            oWorkFlowModel.TableID = (int)ArchiveTableEnum.ArchiveBorrow;
            oWorkFlowModel.FromUserID = new Guid(this.CurrentUser.User_ID);
            oWorkFlowModel.OperateLogID = Guid.NewGuid();
            oWorkFlowModel.RecordID = new Guid(row.DATAID);
            oWorkFlowModel.FromStatusID = new WorkFlowManager().GetOriginalStastuIDByTableID(ArchiveTableEnum.ArchiveBorrow);
            WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
            WorkFlowMessageStatusRule nextRule = ruleCache.GetRuleByStatusIDAndOperateName(oWorkFlowModel.FromStatusID, borrowEnum.ToString());
            oWorkFlowModel.OperateID = nextRule.OperateID;
            WorkFlow oWorkFlow = new WorkFlow();
            //获取本部室领导
            List<Guid> toUserList = this.m_IAuth_User.GetUserDtByOrgIDAndRoleID(this.CurrentUser.ORG_ID, nextRule.ToRoleID.ToString());
            if (toUserList != null && toUserList.Count > 0)
            {
                oWorkFlow.FlowProcess(oWorkFlowModel, toUserList);
            }
            else
            {
                throw new Exception("所驱动到的角色没有用户");
            }
        }
        #endregion

        #region 组合查询
        /// <summary>
        /// 通过档案类型获取表配置类型枚举
        /// </summary>
        /// <returns></returns>
        private ArchiveTableEnum GetArchiveTableEnumByArchiveBaseType()
        {
            //ArchiveTableEnum rtnArchiveTableEnum = ArchiveTableEnum.Account;
            //switch (this.m_ArchiveBaseType)
            //{
            //    case ArchiveBaseType.Account:
            //        rtnArchiveTableEnum = ArchiveTableEnum.Account;
            //        break;
            //    case ArchiveBaseType.AudioVedio:
            //        rtnArchiveTableEnum = ArchiveTableEnum.AudioVedio;
            //        break;
            //    case ArchiveBaseType.BulidProject:
            //        rtnArchiveTableEnum = ArchiveTableEnum.BulidProject;
            //        break;
            //    case ArchiveBaseType.CDKind:
            //        rtnArchiveTableEnum = ArchiveTableEnum.CDKind;
            //        break;
            //    case ArchiveBaseType.Document:
            //        rtnArchiveTableEnum = ArchiveTableEnum.Document;
            //        break;
            //    case ArchiveBaseType.Equipment:
            //        rtnArchiveTableEnum = ArchiveTableEnum.Equipment;
            //        break;
            //    case ArchiveBaseType.OliSearch:
            //        rtnArchiveTableEnum = ArchiveTableEnum.OliSearch;
            //        break;
            //    case ArchiveBaseType.RealKind:
            //        rtnArchiveTableEnum = ArchiveTableEnum.RealKind;
            //        break;
            //    case ArchiveBaseType.Technology:
            //        rtnArchiveTableEnum = ArchiveTableEnum.Technology;
            //        break;
            //    default:
            //        throw new Exception("未知的文档类型");
            //}
            return this.m_ArchiveBaseType;
        }

        /// <summary>
        /// 查询文档数据
        /// </summary>
        /// <returns></returns>
        private DataTable GetTotal()
        {
            return new WorkFlow().GetTotalAll(this.GetArchiveTableEnumByArchiveBaseType(), "");
        }

        protected void OnAfterFiltered_Click(object sender, EventArgs e)
        {
            //this.gv_ArchiveList.DataSource = this.uArchiveFileter.ArchiveFilteredTable;
            //this.gv_ArchiveList.DataBind();
            List<string> colNames = new List<string>();
            if (this.DataSourseScheme != null)
            {
                foreach (DataColumn col in this.DataSourseScheme.Columns)
                {
                    colNames.Add(col.ColumnName);
                }
            }
            this.Where = this.uArchiveFileter.CreateFilterSql(colNames);
            this.pagerdo.CurrentPageIndex = 1;
            BindFilterData();
        }

        protected void OnClearFiltered_Click(object sender, EventArgs e)
        {
            //this.gv_ArchiveList.DataSource = this.GetTotal();
            //this.gv_ArchiveList.DataBind();
            List<string> colNames = new List<string>();
            if (this.DataSourseScheme != null)
            {
                foreach (DataColumn col in this.DataSourseScheme.Columns)
                {
                    colNames.Add(col.ColumnName);
                }
            }
            this.Where = this.uArchiveFileter.CreateFilterSql(colNames);
            this.pagerdo.CurrentPageIndex = 1;
            BindFilterData();
        }
        #endregion

        protected void aspNetPagerSearch_PageChanging(object sender, PageChangingEventArgs e)
        {
            pagerdo.CurrentPageIndex = e.NewPageIndex;
            BindFilterData();
        }

        /// <summary>
        /// 绑定过滤后的数据
        /// </summary>
        private void BindFilterData()
        {
            try
            {
                int beginNum = this.pagerdo.PageSize * (this.pagerdo.CurrentPageIndex - 1);
                int pageSize = this.pagerdo.PageSize;
                int recordCount = 0;
                string filter = this.Where + " and archivetype = " + Request.QueryString["archivetype"];
                if (IsOldArchiveBorrow)
                {
                    //var qzh = UContainer.Resolve<IAuth_User>().GetQZHByUserID(this.CurrentUser.User_ID);
                    var qzh = "DQYT.218";
                    filter += " and fullfondsnum = '" + qzh + "'";
                }
                else
                {
                    var qzh = UContainer.Resolve<IAuth_User>().GetQZHByUserID(this.CurrentUser.User_ID);
                    filter += " and fullfondsnum = '" + qzh + "'";
                }
                DataTable oDataTable = new WorkFlow().GetTotal(this.GetArchiveTableEnumByArchiveBaseType(), beginNum, pageSize, out recordCount, filter, string.Empty);
                if (oDataTable != null)
                {
                    if (this.DataSourseScheme == null)
                    {
                        this.DataSourseScheme = oDataTable.Clone();
                    }
                    SetGridViewEnableField(oDataTable);
                    this.gv_ArchiveList.DataSource = oDataTable;
                    this.gv_ArchiveList.DataBind();
                    this.pagerdo.RecordCount = recordCount;
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        /// <summary>
        /// 组装过滤条件
        /// </summary>
        public string Where
        {
            get
            {
                if (this.ViewState["FilterWhere"] != null)
                {
                    return this.ViewState["FilterWhere"] as string;
                }
                else
                {
                    return " 1=1 "; ;
                }
            }
            set
            {
                this.ViewState["FilterWhere"] = value;
            }
        }

        public DataTable DataSourseScheme
        {
            get
            {
                return this.ViewState["DataSourseScheme"] as DataTable;
            }
            set
            {
                this.ViewState["DataSourseScheme"] = value;
            }
        }

        [Dependency]
        public ISingleWellService m_ISingleWellService
        {
            get;
            set;
        }

        protected void cblARCHIVETYPE_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cblARCHIVETYPE.Items[1].Selected)
            {
                this.btnCreateBorrowSheet.Visible = true;
                this.btnApplyNewRequest.Visible = false;
            }
            else
            {
                this.btnCreateBorrowSheet.Visible = false;
                this.btnApplyNewRequest.Visible = true;
            }
        }
    }

    /// <summary>
    /// 档案打印对象
    /// </summary>
    public class PrintModel
    {
        public string UserName { get; set; }
        public string UserOrg { get; set; }
        public string IDCard { get; set; }
        public string TelNum { get; set; }
        public string ExpridTime { get; set; }
        public string BorrowReason { get; set; }
        public string CopyPage { get; set; }
        public List<string> ArchiveType = new List<string>();
        public List<string> UserType = new List<string>();
        public List<string> DataList = new List<string>();
    }

    public enum BorrowType
    {
        /// <summary>
        /// 厂内借阅
        /// </summary>
        BorrowChangnei = 1,
        /// <summary>
        /// 厂外借阅
        /// </summary>
        BorrowChangwai = 2,
        /// <summary>
        /// 基层借阅
        /// </summary>
        BorrowJiceng = 3,
        /// <summary>
        /// 基层档案员辅助借阅
        /// </summary>
        BorrowJicengdaili = 4
    }
}
